#!/usr/bin/env python3
"""
设备配置调试脚本
用于测试和调试设备配置功能
"""

import json
import sys
import os
import logging

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(__file__))

from services.config_manager import ConfigManager

def test_opcua_device_config():
    """测试OPC UA设备配置"""
    print("🔍 开始测试OPC UA设备配置...")
    
    # 创建测试配置
    test_device = {
        "name": "1#混流泵",
        "description": "测试混流泵设备",
        "type": "opcua",
        "enabled": True,
        "polling_interval": 1000,
        "config": {
            "endpoint": "opc.tcp://192.168.1.100:4840/server",
            "security_policy": "None",
            "username": "",
            "password": ""
        },
        "points": [
            {
                "name": "VD300",
                "description": "变频器频率",
                "node_id": "ns=2;i=300",  # 这是关键！
                "data_type": "float",
                "access": "R"
            },
            {
                "name": "VD304", 
                "description": "变频器电流",
                "node_id": "ns=2;i=304",
                "data_type": "float",
                "access": "R"
            }
        ]
    }
    
    print("📋 测试设备配置:")
    print(json.dumps(test_device, indent=2, ensure_ascii=False))
    
    # 验证配置
    config_manager = ConfigManager()
    validation_errors = config_manager.validate_devices_config([test_device])
    
    print(f"\n🔍 验证结果:")
    if validation_errors:
        print("❌ 验证失败:")
        for error in validation_errors:
            print(f"  - {error}")
    else:
        print("✅ 验证通过！")
    
    # 测试保存
    if not validation_errors:
        print(f"\n💾 测试保存...")
        success = config_manager.save_devices([test_device])
        if success:
            print("✅ 保存成功！")
        else:
            print("❌ 保存失败！")

def test_missing_node_id():
    """测试缺少节点ID的情况"""
    print("\n🔍 测试缺少节点ID的情况...")
    
    # 创建缺少node_id的配置
    bad_device = {
        "name": "坏设备",
        "description": "缺少node_id的设备",
        "type": "opcua",
        "enabled": True,
        "polling_interval": 1000,
        "config": {
            "endpoint": "opc.tcp://192.168.1.100:4840/server",
            "security_policy": "None"
        },
        "points": [
            {
                "name": "VD300",
                "description": "变频器频率",
                # 故意省略node_id
                "data_type": "float",
                "access": "R"
            }
        ]
    }
    
    config_manager = ConfigManager()
    validation_errors = config_manager.validate_devices_config([bad_device])
    
    print(f"🔍 验证结果:")
    if validation_errors:
        print("✅ 正确检测到错误:")
        for error in validation_errors:
            print(f"  - {error}")
    else:
        print("❌ 未能检测到缺少node_id的错误！")

def test_frontend_data_format():
    """测试前端数据格式"""
    print("\n🔍 测试前端发送的数据格式...")
    
    # 模拟前端发送的数据
    frontend_data = {
        "name": "1#混流泵",
        "description": "混流泵测试",
        "type": "opcua",
        "enabled": True,
        "polling_interval": 1000,
        "config": {
            "endpoint": "opc.tcp://192.168.1.100:4840/server",
            "security_policy": "None",
            "username": "",
            "password": ""
        },
        "points": [
            {
                "name": "VD300",
                "description": "变频器频率",
                "node_id": "",  # 空的node_id！这就是问题所在
                "dataType": "float",  # 注意：前端使用dataType而不是data_type
                "access": "R"
            }
        ]
    }
    
    print("📋 前端发送的数据:")
    print(json.dumps(frontend_data, indent=2, ensure_ascii=False))
    
    # 标准化数据格式（模拟服务器端处理）
    normalized_data = normalize_frontend_data(frontend_data)
    
    print("📋 标准化后的数据:")
    print(json.dumps(normalized_data, indent=2, ensure_ascii=False))
    
    # 验证
    config_manager = ConfigManager()
    validation_errors = config_manager.validate_devices_config([normalized_data])
    
    print(f"\n🔍 验证结果:")
    if validation_errors:
        print("❌ 验证失败:")
        for error in validation_errors:
            print(f"  - {error}")
    else:
        print("✅ 验证通过！")

def normalize_frontend_data(frontend_data):
    """标准化前端数据格式"""
    normalized = frontend_data.copy()
    
    # 标准化数据点格式
    if 'points' in normalized:
        for point in normalized['points']:
            # 将dataType转换为data_type
            if 'dataType' in point:
                point['data_type'] = point.pop('dataType')
            
            # 检查空字符串并转换为None
            for key in ['node_id', 'topic', 'address']:
                if key in point and point[key] == '':
                    del point[key]
    
    return normalized

if __name__ == "__main__":
    # 设置日志级别
    logging.basicConfig(level=logging.INFO)
    
    print("🚀 设备配置调试工具")
    print("=" * 50)
    
    # 运行测试
    test_opcua_device_config()
    test_missing_node_id()
    test_frontend_data_format()
    
    print("\n🎯 调试完成！")
    print("\n💡 调试建议:")
    print("1. 检查前端是否正确设置了node_id字段")
    print("2. 检查数据点对象是否包含所有必要字段")
    print("3. 使用浏览器开发者工具查看Network标签页，检查实际发送的数据")
    print("4. 在updateTag函数中添加console.log调试输出") 